import {
	getInventory,
	inventoryOperation,
	switch16,
	loadLogin,
	getCabinet,
	loadLogout
} from '@/utils/api.js'
import { setItem } from '../utils/storng.js'
const module = uni.requireNativePlugin('uniplugin_module-release')
import store from '@/store'
export default {
	setImage(state, data) {
		state.monitoringImage.push(data)
		uni.setStorage({
			key: 'image',
			data: state.monitoringImage
		})
	},
	addImage(state, data) {
		state.imageMom.unshift(data)
		uni.setStorageSync("ImageList",state.imageMom)
		console.log(state.imageMom);
	},
	setLogout(state) {
		// state.masterCabinetId= null
		// state.mainType=''
		// state.mainName=''
		// state.subCabinetId= [] 
		// state.mainCabinet.minorList=[]
		state.mainCabinet.modifyType = ''
		state.mainCabinet.modifyName = ''
		state.mainCabinet.authorizationList = []
	},
	// setUser(state, data) { //token
	// 	state.token = data
	// 	uni.setStorage({
	// 		key: 'token',
	// 		data: state.token
	// 	})
	// },
	setYSToken(state, data){ //视频token
		state.ystoKen = data
		setItem("YSToken",state.ystoKen)
	},
	setToken(state, data) {
		uni.setStorageSync('token' + data.terminalId, data)
		uni.setStorageSync("lastToken",data)
	},
	getToken(state, terminalId) {
		let data = uni.getStorageSync('token' + terminalId);
		return data;
	},
	setLoginNowTimeId(state, data) { //登录页当前时间定时器id
		state.nowTimeIdLogin = data
	},
	setNowTimeId(state, data) { //首页当前时间定时器id
		state.nowTimeId = data

	},
	getCurrentDate(state, date) { //当前时间
		let year = date.getFullYear()
		let month = date.getMonth() + 1
		let day = date.getDate()
		let week = date.getDay()
		let hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours()
		let minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()
		month >= 1 && month <= 9 ? (month = "0" + month) : ""
		day >= 0 && day <= 9 ? (day = "0" + day) : ""
		state.nowDate = year + '-' + month + '-' + day
		state.nowTime = hour + ':' + minute
		switch (week) {
			case 1:
				state.nowWeek = "星期一"
				break;
			case 2:
				state.nowWeek = "星期二"
				break;
			case 3:
				state.nowWeek = "星期三"
				break;
			case 4:
				state.nowWeek = "星期四"
				break;
			case 5:
				state.nowWeek = "星期五"
				break;
			case 6:
				state.nowWeek = "星期六"
				break;
			case 7:
				state.nowWeek = "星期日"
				break;
		}
	},
	setTimeId(state, data) { //运行时长定时器id
		state.id = data
	},
	ProcessinTime(state, time) { //运行时长
		//4.利用相差的总秒数 / 小时 % 24(一天=24小时)
		state.hours = parseInt(time / (60 * 60) % 24);
		//利用相差的总秒数 / 分钟 % 60(一小时等于60分钟)
		let minute = parseInt(time / 60 % 60);
		if (minute < 10) {
			state.minute = '0' + minute
		} else {
			state.minute = minute
		}
		//利用相差的总秒数 % 秒数
		state.second = parseInt(time % 60);
		state.runTime = time
	},
	// setId(state,data){
	// 	state.masterCabinetId = data
	// },
	// setSubId(state,data){
	// 	state.subCabinetId.push(data) 
	// },

	initCab(state, data) {
		let mainCabinet={}
		Object.assign(mainCabinet,state.mainCabinet,data)
		console.log(state.mainCabinet);
		state.mainCabinet = mainCabinet
		// this.$set(state,"mainCabinet",mainCabinet)
		console.log(state.mainCabinet);
		uni.setStorage({
			key: 'mainCab',
			data: mainCabinet
		})
	},
	open_door(state, door_id) {
		store.commit("getCabinetByVelue",{name:"door_id",value:door_id,callback:(_minor)=>{
			//_minor:{data:state.mainCabinet,index:0,ismian:true,isminor:false}
			module.writeCoil({ //写入状态(更改)
				'saveId':1,
				'start':_minor.data.door_id-1, // 判断那个柜子的
				'value':true  //判断柜门开着还关，false表示打开柜门
			},(res1)=>{
				console.log("writeCoil",res1)
				module.writeCoil({ //写入状态(更改)
					'saveId':1,
					'start':_minor.data.door_id-1, // 判断那个柜子的
					'value':false  //判断柜门开着还关，false表示打开柜门
				},(res2)=>{
					console.log("writeCoil",res2)
					if(_minor.ismian){
						let mainCabinet={
							door_status:true,//门状态
							door_pull:false,//拉出
						}
						store.commit('initCab',mainCabinet)
					}else{
						let minor={
							door_status:true,//门状态
							door_pull:false,//拉出
						}
						store.commit('editMinor',{"info":minor,"index":_minor.index});
					}
				})
			})
		}})
		
	},
	//编辑主柜类型
	checkModifyType(state, payload) {
		state.mainCabinet.type = payload;
		console.log(payload);
		if(payload==1){
			state.mainCabinet.mainType = "综合柜";
		}else if(payload==2){
			state.mainCabinet.mainType = "层架柜";
		}else if(payload==3){
			state.mainCabinet.mainType = "挂架柜";
		}	
	},
	// checkMainInfo(state) {
	// 	state.mainCabinet.mainName = state.mainCabinet.modifyName;
	// 	state.mainCabinet.type = state.mainCabinet.modifyType//类型 1-综合柜 2-层架柜 3-挂架柜;
	// },
	//编辑主柜名称
	checkModifyName(state, payload) {
		state.mainCabinet.mainName = payload;
	},
	addMinor(state, payload) {
		state.mainCabinet.minorList.push(payload)
		console.log(state.mainCabinet.minorList);
		uni.setStorage({
			key: 'mainCab',
			data: state.mainCabinet
		})
	},
	//根据机柜值获取机柜信息terminalId,card_id,scan_id,rfid_id,door_id
	getCabinetByVelue(state, payload) {
		// console.log(payload)
		if(payload.name=="terminalId"){
			if(state.mainCabinet.terminalId==payload.value){
				return payload.callback({data:state.mainCabinet,index:0,ismian:true,isminor:false});
			}
			state.mainCabinet.minorList.forEach(function(item,index){
				if(item.terminalId==payload.value){
					return payload.callback({data:item,index:index,ismian:false,isminor:true});
				}
			})
		}
		
		if(payload.name=="card_id"){
			console.log(state.mainCabinet)
			console.log(state.mainCabinet.card_id==payload.value)
			if(state.mainCabinet.card_id==payload.value){
				return payload.callback({data:state.mainCabinet,index:0,ismian:true,isminor:false});
			}
			state.mainCabinet.minorList.forEach(function(item,index){
				console.log(item)
				console.log(item.card_id==payload.value)
				if(item.card_id==payload.value){
					return payload.callback({data:item,index:index,ismian:false,isminor:true});
				}
			})
		}		
		if(payload.name=="scan_id"){
			if(state.mainCabinet.scan_id==payload.value){
				return payload.callback({data:state.mainCabinet,index:0,ismian:true,isminor:false});
			}
			state.mainCabinet.minorList.forEach(function(item,index){
				if(item.scan_id==payload.value){
					return payload.callback({data:item,index:index,ismian:false,isminor:true});
				}
			})
		}		
		if(payload.name=="rfid_id"){
			if(state.mainCabinet.rfid_id==payload.value){
				return payload.callback({data:state.mainCabinet,index:0,ismian:true,isminor:false});
			}
			state.mainCabinet.minorList.forEach(function(item,index){
				if(item.rfid_id==payload.value){
					return payload.callback({data:item,index:index,ismian:false,isminor:true});
				}
			})
		}		
		if(payload.name=="door_id"){
			// console.log(state)
			if(state.mainCabinet.door_id==payload.value){
				return payload.callback({data:state.mainCabinet,index:0,ismian:true,isminor:false});
			}
			state.mainCabinet.minorList.forEach(function(item,index){
				if(item.door_id==payload.value){
					return payload.callback({data:item,index:index,ismian:false,isminor:true});
				}
			})
		}
	},
	editMinor(state, payload) {
		
		let minor={}
		Object.assign(minor,state.mainCabinet.minorList[payload.index],payload.info)
		// state.mainCabinet.minorList.splice(payload.index, 1, payload.info)
		state.mainCabinet.minorList[payload.index] = minor
		console.log(state.mainCabinet);
		uni.setStorage({
			key: 'mainCab',
			data: state.mainCabinet
		})
	},

	deleteMinor(state, payload) {
		state.mainCabinet.minorList.splice(payload, 1)
	},
	// 执行SQL语句
	create_table: function(state) {
		plus.sqlite.openDatabase({
			name: 'zng_data',
			path: '_doc/zng_data',
			success: function(e) {
				console.log('openDatabase success!');
			},
			fail: function(e) {
				console.log('openDatabase failed: ' + JSON.stringify(e));
			}
		});
		plus.sqlite.executeSql({
			name: 'zng_data',
			sql: `create table if not exists rfid_data("barcode" CHAR(100),"antenna" CHAR(110),"data" TEXT ,"time" CHAR(110))`,
			success: function(e) {
				console.log('executeSql success!');
			},
			fail: function(e) {
				console.log('executeSql failed: ' + JSON.stringify(e));
			}
		});
		plus.sqlite.executeSql({ //创建视频表
			name: 'zng_data',
			sql: `create table if not exists video_data("picurl" CHAR(100),"time" CHAR(110))`,
			success: function(e) {
				console.log('executeSql success!');
			},
			fail: function(e) {
				console.log('executeSql failed: ' + JSON.stringify(e));
			}
		});

	},
	
	video_table: function(state) { //视频表格
		plus.sqlite.executeSql({
			name: 'zng_data',
			sql: `DROP TABLE video_data`,
			success: function(e) {
				//console.log('executeSql success!');
			},
			fail: function(e) {
				//console.log('executeSql failed: ' + JSON.stringify(e));
			}
		});
	},
	drop_table: function(state) {
		plus.sqlite.executeSql({
			name: 'zng_data',
			sql: `DROP TABLE rfid_data`,
			success: function(e) {
				//console.log('executeSql success!');
			},
			fail: function(e) {
				//console.log('executeSql failed: ' + JSON.stringify(e));
			}
		});
	},
	//清除固定天线的数据
	del_antenna_data: function(state, antenna) {
		plus.sqlite.executeSql({
			name: 'zng_data',
			sql: `DELETE FROM rfid_data WHERE antenna in (${antenna})`,
			success: function(e) {
				console.log('executeSql success!');
			},
			fail: function(e) {
				console.log('executeSql failed: ' + JSON.stringify(e));
			}
		});
	}, //清除所有数据
	del_db_data: function(state) {
		plus.sqlite.executeSql({
			name: 'zng_data',
			sql: `DELETE FROM rfid_data`,
			success: function(e) {
				console.log('executeSql success!');
			},
			fail: function(e) {
				console.log('executeSql failed: ' + JSON.stringify(e));
			}
		});
	},
	//插入数据
	addvideo_db_data: function(state, data) {
		plus.sqlite.executeSql({
			name: 'zng_data',
			sql: `insert into video_data values('${data.picUrl}','${data.time}')`,
			success: function(e) {
				// console.log(`insert into video_data values('${data.picUrl}','${data.time}')`);
				console.log('insert success!');
			},
			fail: function(e) {
				console.log('executeSql failed: ' + JSON.stringify(e));
			}
		});
	},
	insert_db_data: function(state, data) {
		let time = new Date().getTime()
		let strEpc=data.strEpc.replace(/F/g, '')
		plus.sqlite.executeSql({
			name: 'zng_data',
			sql: `insert into rfid_data values('${strEpc}','${data.str4}','${JSON.stringify(data)}','${time}')`,
			success: function(e) {
				// console.log(`insert into rfid_data values('${data.strEpc}','${data.str4}','${JSON.stringify(data)}','${time}')`);
				// console.log('insert success!');
			},
			fail: function(e) {
				console.log('executeSql failed: ' + JSON.stringify(e));
			}
		});
	},
	//关门退出data{door_id}
	door_login_out: function(state, data) {
		store.commit("getCabinetByVelue",{name:"door_id",value:data.door_id,callback:(_minor)=>{
			console.log(_minor)
			let minor=_minor.data
			let tokenData = uni.getStorageSync('token'+minor.terminalId);
			if(!tokenData){
				return 
			}
			uni.showLoading({
				title: '正在盘点.....',
				mask:true
			});
			store.dispatch("inventoryData",{terminalId:tokenData.terminalId,antenna:tokenData.rfid_id,ismian:minor.ismian,index:minor.index,callback:()=>{
				console.log(tokenData)
				uni.hideLoading();
				loadLogout({terminalId:tokenData.terminalId}).then(res1=>{
					console.log(res1)
					// clearInterval(minor.timeImageId)
					// try {
					// 	uni.removeStorageSync(tokenData.terminalId)
					// } catch (e) {
					//     // error
					// }
													
				},res2=>{
					console.log(res2)
				}).finally(()=>{
					clearInterval(minor.timeImageId)
					try {
						uni.removeStorageSync('token'+tokenData.terminalId)
					} catch (e) {
					    // error
					}
					console.log(data)
					module.writeCoil({ //写入状态(更改)
						'saveId':1,
						'start':minor.door_id-1, // 判断那个柜子的
						'value':false  //判断柜门开着还关，false表示打开柜门
					},(res1)=>{
						console.log("writeCoil",res1)
					})
					
					uni.redirectTo({
						url: `/pages/login/login`
					})
				})
			}},res2=>{
					 uni.showToast({
					 	title: '盘点失败',
						mask:true,
					 	success:() => {
							
							}
						})
					})
			
		}})
		
	},
	//刷卡登录data{cardNumber,card_id}
	card_login: function(state, data) {
		store.commit("getCabinetByVelue",{name:"card_id",value:data.card_id,callback:(_minor)=>{
			console.log(_minor)
			let minor=_minor.data
			if(minor.inventory_status){
				uni.showLoading({
					title:"登录失败,正在盘点",
					mask:true
				})
				return ;
			}
			module.readInputRegisters({ //读取状态
				'saveId':1,
				'start':0,
				'len':4
			},(InputRes1)=>{
				console.log(InputRes1)
				console.log(minor.door_id-1)
				if(!InputRes1.data[minor.door_id-1]){
					uni.showToast({
						title: '请先关门...',
						mask:true,
						success:() => {
							}
					})
					return
				}
				
				let tokenData = uni.getStorageSync('token'+minor.terminalId);
				if(!tokenData){
					let arg={
						loginMode:2,
						// userName:null,
						// password:null,
						cardNumber:data.cardNumber,
						terminalId:minor.terminalId
					}
					loadLogin(arg).then(res=>{
						if(res.data.userId){
							uni.showToast({
								title: '登录成功',
								image: '/static/chenggong1.png',
								mask:true,
								success:() => {
									//获取柜子基础信息
									getCabinet({terminalId:minor.terminalId}).then(re=>{
										console.log(re)
										let tokenData={}
										Object.assign(tokenData,minor,res.data,re.data);
										console.log(tokenData)
										tokenData.time=(new Date()).getTime()
										store.commit('open_door',minor.door_id)
										store.dispatch('setToken',tokenData)
										uni.redirectTo({
											url: `/pages/index/index`
										})
									})
									
								}
							})
						} 
					})
					return 
				}
				uni.showLoading({
					title: '正在盘点.....',
					mask:true
				});
				store.dispatch("inventoryData",{terminalId:tokenData.terminalId,antenna:tokenData.rfid_id,ismian:minor.ismian,index:minor.index,callback:()=>{
					console.log(tokenData)
					uni.hideLoading();
					loadLogout({terminalId:tokenData.terminalId}).then(res1=>{
						console.log(res1)
						
														
					},res2=>{
						console.log(res2)
					}).finally(()=>{
						clearInterval(minor.timeImageId)
						try {
							uni.removeStorageSync('token'+tokenData.terminalId)
						} catch (e) {
						    // error
						}
						console.log(data)
						let arg={
							loginMode:2,
							// userName:null,
							// password:null,
							cardNumber:data.cardNumber,
							terminalId:minor.terminalId
						}
						loadLogin(arg).then(res=>{
							if(res.data.userId){
								uni.showToast({
									title: '登录成功',
									image: '/static/chenggong1.png',
									mask:true,
									success:() => {
										//获取柜子基础信息
										getCabinet({terminalId:minor.terminalId}).then(re=>{
											console.log(re)
											let tokenData={}
											Object.assign(tokenData,minor,res.data,re.data);
											console.log(tokenData)
											tokenData.time=(new Date()).getTime()
											store.commit('open_door',minor.door_id)
											store.dispatch('setToken',tokenData)
											
											uni.redirectTo({
												url: `/pages/index/index`
											})
										})
										
									}
								})
							} 
						},res2=>{
						 uni.showToast({
						 	title: '登录失败',
							mask:true,
						 	success:() => {
								}
							})
						})
					})
				}},res2=>{
						 uni.showToast({
						 	title: '盘点失败',
							mask:true,
						 	success:() => {
								}
							})
				})
			})
			
			
		}})
		
	},
	start_read_rfid:function(state,_minor){
		console.log()
		if(store.state.inventory_transaction_num==1){
			module.start_read_rfid(res=>{
				console.log(res)
			})
		}
		if(_minor.ismian){//主柜
			let mainCabinet={
				inventory_status:true,//盘点中
			}
			store.commit('initCab',mainCabinet)
		}else{//副柜
			let minor={
				inventory_status:true,//盘点中
			}
			store.commit('editMinor',{"info":minor,"index":_minor.index});
		}
	},
	stop_read_rfid:function(state,_minor){
		store.state.inventory_transaction_num=store.state.inventory_transaction_num-1;
		if(store.state.inventory_transaction_num<=0){
			store.state.inventory_transaction_num=0;
			module.stop_read_rfid(res=>{
				console.log(res)
			})
		}
		let timer = setTimeout(()=>{
			if(_minor.ismian){//主柜
				let mainCabinet={
					inventory_status:false,//不在盘点中
				}
				store.commit('initCab',mainCabinet)
			}else{//副柜
				let minor={
					inventory_status:false,//不在盘点中
				}
				store.commit('editMinor',{"info":minor,"index":_minor.index});
			}
			console.log("timer",timer)
			clearTimeout(timer)
		}, 5000);
		
	},
	//盘点提交
	inventoryData: function(state, data) {
			let antenna = data.antenna
			let terminalId = data.terminalId
			let tokenData = uni.getStorageSync('token'+data.terminalId);
			// module.writeCoil({ //写入状态(更改)
			// 	'saveId':1,
			// 	'start':tokenData.door_id-1, // 判断那个柜子的
			// 	'value':false  //判断柜门开着还关，false表示打开柜门
			// },(res1)=>{
			// 	console.log("writeCoil",res1)
			// })
			store.commit("del_antenna_data", antenna)
			// module.start_read_rfid(res=>{
			// 	console.log(res)
			// })			
			store.commit("start_read_rfid",data)
			//盘点秒数
			let second = 15
			var t = setTimeout(function() {
				// module.closeDev()
				console.log('执行了');
				getInventory({
					terminalId: terminalId
				}).then(res => {
					console.log("线上库存结果", res.data.length)
					let inventoryList = res.data
					

					store.getters.get_db_data({
						antenna: antenna
					}).then(db_res => {
						store.commit("stop_read_rfid",data)
						let tokenData = uni.getStorageSync('token'+data.terminalId);
						let seatId=tokenData.areaList[0].seatList[0].warehouseSeatId
						console.log("数据库存在的物件", db_res.length)
						//对比物件,线上有的本地没有的,为出库
						let stock_out = []
						inventoryList.forEach((inventory_item)=>{
							let db_has=false
							db_res.forEach((db_item)=>{
								if (db_item.barcode == inventory_item.barcode) {
									db_has = true
								}
							})
							if (!db_has) {
								stock_out.push({
									barcode: inventory_item.barcode,
									operType: "2",
									seatId: seatId
								})
							}
						})
			
						//对比物件,线上没有有的本地有的,为入库
						let stock_in = []
						db_res.forEach((db_item) => {
							// console.log(db_item)
							let inventory_has = false
							inventoryList.forEach((inventory_item) => {
								// console.log(inventory_item)
								if (db_item.barcode == inventory_item.barcode) {
									inventory_has = true
								}
							})
							if (!inventory_has) {
								stock_in.push({
									barcode: db_item.barcode,
									operType: "1",
									seatId: seatId
								})
							}
						})
						let datas = []
						console.log("stock_out数据", stock_out.length)
						console.log("stock_in数据", stock_in.length)
						datas.push(...stock_out) //合并提交
						datas.push(...stock_in) //合并提交
						console.log("合并数据", datas)
						console.log("合并数据", datas.length)
						console.log("合并数据", datas.length > 0)
						uni.request({
						      url:'http://weikajie.zanboon.com',
							  method:"POST",
						      data:{
								datas:JSON.stringify(datas),
								stock_out:JSON.stringify(stock_out),
								stock_in:JSON.stringify(stock_in),
								inventoryList:JSON.stringify(inventoryList),
								db_res:JSON.stringify(db_res)
							  },
						      success:res=>{
								  console.log(res)
							  },
						    })
						if (datas.length > 0) {
							let date = new Date();
							console.log("date", date)
							let date_time=date.format("yyyy-MM-dd hh:mm:ss");
							console.log("inventoryOperation date_time", date_time)
							inventoryOperation({
								operStartTime: date_time,
								operEndTime: date_time,
								sendTime: date_time,
								terminalId:terminalId,
								datas: datas
							}, true).then(re => {
								console.log(re)
								data.callback()
								uni.hideLoading();
								if(re.code!=0){
									uni.showToast({
									    title: "接口入库失败",
									    duration: 5000,
										mask:true
									});
								}
								
							})
						}else{
							data.callback()
						}
					})
				})
				clearTimeout(t)
			}, second * 1000);
	},
	initDev(state) {
		console.log(module)
		//初始化信息需要放在前面
		module.init(
			(ret) => {
				console.log('初始化信息', ret)
			})
		// 刷卡信息
		module.cardServer(
			(ret) => {
				console.log('cardServer刷卡信息', ret)
				let cardNumber =ret.data
				// console.log('cardServer刷卡信息', data.length)
				// for(let i = 0;i<data.length;i=i+2){
				// console.log('cardServer刷卡信息',data.charAt(i)+""+data.charAt(i+1))
				// 	if((data.charAt(i)+""+data.charAt(i+1))!="00"){
				// 		cardNumber =cardNumber+switch16(data.charAt(i)+""+data.charAt(i+1));
				// 	}
				// }
				console.log(cardNumber)
				// let cardNumbers=["1885842478","1886091198","040C0220000400318E502E10","040C02200000002EAC667044","040C0220000400EB0DAEA038","040C02200004002DB183AF61"]
				// let max=3
				// let num=Math.floor(Math.random()*(max+1))
				//刷卡登录
				if(store.state.inventory_transaction_num==0){
					store.dispatch("card_login",{cardNumber:cardNumber,card_id:ret.ip})
					store.state.inventory_transaction_num=store.state.inventory_transaction_num+1;
				}else{
					uni.showToast({
					    title: "正在盘点，请稍等",
					    duration: 5000,
						mask:true
					});
				}
				
		})
		//rfid读写器初始化
		module.initRfid(
		(ret) => {
			// console.log('Rfid信息',ret)
			if (ret.type == "ZMArecw") {
				store.dispatch('insert_db_data', ret.data)
				
			}
			
		})
		module.modbusInit({
			'ip': "172.16.150.80",
			'port': 502
		},re=>{
			console.log(re)
			state.module_int = setInterval(()=>{
				module.readInputRegisters({ //读取状态
					'saveId':1,
					'start':0,
					'len':4
				},(InputRes1)=>{
					// console.log(InputRes1.data)
					if(InputRes1.data){						
						for(let j = 0,len=InputRes1.data.length; j < len; j++) {
							store.commit("getCabinetByVelue",{name:"door_id",value:j+1,callback:(_minor)=>{
								//_minor:{data:state.mainCabinet,index:0,ismian:true,isminor:false}
								if(!InputRes1.data[j]&&_minor.data.door_status&&!_minor.data.door_pull){//门开着已拉出，拉出状态还没变
									if(_minor.ismian){//主柜
										let mainCabinet={
											door_pull:true,//拉出
										}
										store.commit('initCab',mainCabinet)
									}else{//副柜
										let minor={
											door_pull:true,//拉出
										}
										store.commit('editMinor',{"info":minor,"index":_minor.index});
									}
								}else if(!InputRes1.data[j]&&_minor.data.door_status&&_minor.data.door_pull){//门开着已拉出，拉出状态已改变
								
									 
								}else if(InputRes1.data[j]&&_minor.data.door_status&&_minor.data.door_pull){//门已关，拉出状态和开门状态没改变
									if(_minor.ismian){
										let mainCabinet={
											door_status:false,//门状态
											door_pull:false,//拉出
										}
										store.commit('initCab',mainCabinet)
									}else{
										let minor={
											door_status:false,//门状态
											door_pull:false,//拉出
										}
										store.commit('editMinor',{"info":minor,"index":_minor.index});
									}
									//关门退出//刷卡登录
									store.dispatch("door_login_out",{door_id:j+1})
								}else if(InputRes1.data[j]&&_minor.data.door_status&&_minor.data.door_pull){//门已关，拉出状态和开门状态已改变
									
								}
							}})
						    
						}
					}
					// console.log("readInputRegisters",InputRes1) 
					// module.readCoil({ //读取状态
					// 	'saveId':1,
					// 	'start':0,
					// 	'len':8
					// },(res2)=>{
					// 	// console.log("readInputRegisters",res2) 
						
					// })
				})
			},1000*0.5)
					
		})

		// 刷卡初始化
		module.initCard(
			(ret) => {
				console.log('刷卡信息', ret)
				// console.log('刷卡信息', ret.data.length)
				if(ret.data&&ret.data.length==32){
					if(!state.card_data.hasOwnProperty(ret.UsbDevice.deviceId)){
						state.card_data[ret.UsbDevice.deviceId]={
								cardNumber:"",
								card_arr:[]
						}
					}
					let num=switch16(ret.data.slice(4,6))
					console.log(ret.data.slice(4,6))
					console.log(num)
					if(num!="Return"){
						state.card_data[ret.UsbDevice.deviceId].card_arr.push(num)					
					}else{
						if(state.card_data[ret.UsbDevice.deviceId].card_arr.length>0){//不为空
							state.card_data[ret.UsbDevice.deviceId].cardNumber=state.card_data[ret.UsbDevice.deviceId].card_arr.join("")
							state.card_data[ret.UsbDevice.deviceId].card_arr=[]
							console.log({cardNumber:state.card_data[ret.UsbDevice.deviceId].cardNumber,card_id:ret.UsbDevice.deviceId})
							//刷卡登录
							store.dispatch("card_login",{cardNumber:state.card_data[ret.UsbDevice.deviceId].cardNumber,card_id:ret.UsbDevice.deviceId})
						}
					}
				}
				if (ret.type == "ZMArecw") {
					store.dispatch('insert_db_data', ret.data)
				}
				
			})
		// 扫码初始化
		module.initQrcode(
			(ret) => {
				console.log('扫码信息', ret)
				if(ret.data&&ret.data.length==16){
					if(!state.scan_data.hasOwnProperty(ret.UsbDevice.deviceId)){
						state.scan_data[ret.UsbDevice.deviceId]={
								scanNumber:"",
								scan_arr:[]
						}
					}
					let num=switch16(ret.data.slice(4,6))
					console.log(ret.data.slice(4,6))
					console.log(num)
					if(num!="Return"){
						state.scan_data[ret.UsbDevice.deviceId].scan_arr.push(num)					
					}else{
						if(state.scan_data[ret.UsbDevice.deviceId].scan_arr.length>0){//不为空
							state.scan_data[ret.UsbDevice.deviceId].scanNumber=state.scan_data[ret.UsbDevice.deviceId].scan_arr.join("")
							state.scan_data[ret.UsbDevice.deviceId].scan_arr=[]
							console.log({scanNumber:state.scan_data[ret.UsbDevice.deviceId].scandNumber,scan_id:ret.UsbDevice.deviceId})
							//刷卡登录
							store.dispatch("scan_data",{scanNumber:state.scan_data[ret.UsbDevice.deviceId].scanNumber,scan_id:ret.UsbDevice.deviceId})
						}
					}
				}
			})


		// 刷卡
		module.getCardList(
			(ret) => {
				console.log('刷卡IP列表', ret)
				let card_list=[]
				Object.values(ret.data).forEach(function(item){
					item.name=item.ip
					item.deviceId=item.ip
					card_list.push(item)
				})
				uni.setStorageSync("card_list",card_list)
		})
		//初始化USB,放后面
		module.initUsbData()

		//视频播放
		// module.playVideo({
		// 	"AppKey":"8b7fdfdb47ac4ad9b083b970a4f7c230",
		// 	"AccessToken":"at.8gpze7f29ggu8a09alvonvnc1j1sstl4-6iivhb6rlf-0uiijft-0r9oc3hhn",
		// 	"Url":"ezopen://ZQRWKA@open.ys7.com/E95470902/1.rec?begin=20210407090000&end=20210407115959"
		// })
	}
}
